package com.bci.pwtz.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import com.bci.pwtz.common.util.PaginationList;
import com.bci.pwtz.common.util.PwtzUtils;
import com.bci.pwtz.exception.CanNotDeleteException;
import com.bci.pwtz.exception.PwtzDatabaseException;
import com.bci.pwtz.mysql.dao.DygtMapper;
import com.bci.pwtz.mysql.model.Dygt;
import com.bci.pwtz.service.BusinessRefService;
import com.bci.pwtz.service.CompanyService;
import com.bci.pwtz.service.DygtService;

@Service
public class DygtServiceImpl implements DygtService {
	private DygtMapper objMapper;
	private BusinessRefService businessRefService;
	private CompanyService companyService;
	public void setObjMapper(DygtMapper objMapper){
		this.objMapper=objMapper;
	}
	
	public DygtMapper getObjMapper(){
		return objMapper;
	}
	private static final Logger _logger=Logger.getLogger(DygtServiceImpl.class);

	public BusinessRefService getBusinessRefService()
    {
        return businessRefService;
    }

    public void setBusinessRefService(BusinessRefService businessRefService)
    {
        this.businessRefService = businessRefService;
    }

    public CompanyService getCompanyService() {
		return companyService;
	}

	public void setCompanyService(CompanyService companyService) {
		this.companyService = companyService;
	}

	@Override
	public Dygt add(Dygt dygt) throws PwtzDatabaseException {
		Date modifytime=new Date();
		if(_logger.isDebugEnabled()){
			_logger.debug("add:dygt="+dygt.toString());
		}
		if(dygt==null){
			if(_logger.isDebugEnabled()){
				_logger.debug("add,dygt is null");
			}
			return null;
		}else{
			/*UUID uuid=UUID.randomUUID();
			dygt.setDeviceid(uuid.toString());*/
			dygt.setStatus(1);
			dygt.setCreatedate(modifytime);
			dygt.setLastmodifiedtime(modifytime);
		}
		try{
			if(dygt.getDeviceid().equals(dygt.getPhysicaltowercode())){
				dygt.setIssametower("否");
				dygt.setNote(dygt.getDevicename());
			}else{
				dygt.setIssametower("是");
			}
		    List<Dygt> list=objMapper.getSameTowerList(dygt.getPhysicaltowercode());
		    dygt.setSametowernumber(list.size()+1);
			objMapper.insertSelective(dygt);
		    StringBuffer towername=new StringBuffer();
		    if(list!=null&&list.size()>0){
		    	for(Dygt d:list){
			    	if(d.getDeviceid().equals(dygt.getPhysicaltowercode())){
			    		continue;
			    	}
			        d.setSametowernumber(list.size()+1);
			        d.setLastmodifiedtime(modifytime);
			        d.setLastoperatorid(dygt.getLastoperatorid());
			        towername.append("-"+d.getDevicename());
			        objMapper.updateByPrimaryKeySelective(d);
			    }
		    	Dygt physicaltower=objMapper.selectByPrimaryKey(dygt.getPhysicaltowercode());
			    if(list.size()==1){
			    	physicaltower.setIssametower("是");
			    }
			    physicaltower.setSametowernumber(list.size()+1);
			    physicaltower.setNote(physicaltower.getDevicename()+towername.toString()+"-"+dygt.getDevicename());
			    objMapper.updateByPrimaryKeySelective(physicaltower);
		    }
		}catch(DataAccessException e){
			_logger.error(ExceptionUtils.getStackTrace(e));
			throw new PwtzDatabaseException();
		}
		return dygt;
	}

	@Override
	public int delete(String deviceId) throws PwtzDatabaseException, CanNotDeleteException {
		if(_logger.isDebugEnabled()){
			_logger.debug("delete:deviceId="+deviceId);
		}
		int result=0;
		Date modifytime=new Date();
		try{
			boolean bl=businessRefService.canDelete("T_DYGT", deviceId);
			if(!bl){
				throw new CanNotDeleteException();
			}
			Dygt device=load(deviceId);
			result=objMapper.deleteById(deviceId,modifytime);
			if(result>0&&!device.getDeviceid().equals(device.getPhysicaltowercode())){
			   List<Dygt> list=objMapper.getSameTowerList(device.getPhysicaltowercode());
			   if(list!=null&&list.size()>0){
				   StringBuffer sametower=new StringBuffer();
			       for(Dygt d : list){
			    	   if(d.getDeviceid().equals(device.getPhysicaltowercode())){
			    		   continue;
			    	   }
			           d.setSametowernumber(list.size());
			           d.setLastmodifiedtime(modifytime);
			           objMapper.updateByPrimaryKeySelective(d);
			           sametower.append("-"+d.getDevicename());
			       }
			       //物理杆名称变更
			       Dygt physicaltower=load(device.getPhysicaltowercode());
			       if(list.size()==1){
			    	   physicaltower.setIssametower("否");
			       }
			       physicaltower.setLastmodifiedtime(modifytime);
			       physicaltower.setNote(physicaltower.getDevicename()+sametower.toString());
			       objMapper.updateByPrimaryKeySelective(physicaltower);
			   }
			}
		}catch(DataAccessException e){
			_logger.error(ExceptionUtils.getStackTrace(e));
			throw new PwtzDatabaseException();
		}
		return result;
	}

	@Override
	public int update(Dygt dygt) throws PwtzDatabaseException {
		int result=0;
		Date modifytime=new Date();
		if(_logger.isDebugEnabled()){
			_logger.debug("update:dygt="+dygt.toString());
		}
		if(dygt==null){
			if(_logger.isDebugEnabled()){
				_logger.debug("update,dygt is null");
			}
			return result;
		}else{
		    dygt.setLastmodifiedtime(modifytime);
		}
		try{
		    Dygt obj=load(dygt.getDeviceid());
		    if(obj==null){
		        return 0;
		    }
		    List<Dygt> list=null;
		    //虚拟杆转物理杆
		    if(dygt.getPhysicaltowercode().equals(dygt.getDeviceid())&&!(dygt.getDeviceid().equals(obj.getPhysicaltowercode()))){
		        dygt.setIssametower("否");
		        dygt.setSametowernumber(1);
		        result=objMapper.updateByPrimaryKeySelective(dygt);
		        list=objMapper.getSameTowerList(obj.getPhysicaltowercode());
		        StringBuffer sametower=new StringBuffer();
		        if(list!=null&&list.size()>0){
		        	for(Dygt d:list){
			        	if(d.getDeviceid().equals(obj.getPhysicaltowercode())){
			        		continue;
			        	}
			            d.setSametowernumber(list.size());
			            d.setLastmodifiedtime(new Date());
			            d.setLastoperatorid(dygt.getLastoperatorid());
			            objMapper.updateByPrimaryKeySelective(d);
			            sametower.append("-"+d.getDevicename());
			        }
			        Dygt physicaltower=load(obj.getPhysicaltowercode());
			        if(list.size()==1){
			        	physicaltower.setIssametower("否");
			        }
			        physicaltower.setSametowernumber(list.size());
			        physicaltower.setLastmodifiedtime(modifytime);
			        physicaltower.setLastoperatorid(dygt.getLastoperatorid());
			        physicaltower.setNote(physicaltower.getDevicename()+sametower.toString());
			        objMapper.updateByPrimaryKeySelective(physicaltower);
		        }
		    }
		    //物理杆转虚拟杆
		    else if(!(dygt.getPhysicaltowercode().equals(dygt.getDeviceid()))&&obj.getDeviceid().equals(obj.getPhysicaltowercode())){
		    	List<Dygt> olist=objMapper.getSameTowerList(obj.getDeviceid());
		    	if(olist!=null&&olist.size()>1){
		    		return 0;
		    	}
//		        if(olist.size()==1){
//		            dygt.setIssametower("是");
//		        }
		        list=objMapper.getSameTowerList(dygt.getPhysicaltowercode());
		        dygt.setSametowernumber(list.size()+1);
		        dygt.setIssametower("是");
		        dygt.setNote("");
                result=objMapper.updateByPrimaryKeySelective(dygt);
		        if(list.size()==0){
		            return 0;
		        }
                StringBuffer sametower=new StringBuffer();
//		            list.addAll(olist);
//	            list.remove(obj);
		        if(list!=null&&list.size()>0){
		        	for(Dygt d:list){
			        	if(d.getDeviceid().equals(dygt.getPhysicaltowercode())){
			        		continue;
			        	}
			            d.setSametowernumber(list.size()+1);
//	    		            d.setPhysicaltowercode(dygt.getPhysicaltowercode());
			            d.setLastmodifiedtime(modifytime);
			            d.setLastoperatorid(dygt.getLastoperatorid());
			            objMapper.updateByPrimaryKeySelective(d);
		                sametower.append(d.getDevicename());
			        }
			        Dygt physicaltower=load(dygt.getPhysicaltowercode());
			        if(list.size()==1){
			        	physicaltower.setIssametower("是");
			        }
			        physicaltower.setSametowernumber(list.size());
			        physicaltower.setLastmodifiedtime(modifytime);
			        physicaltower.setLastoperatorid(dygt.getLastoperatorid());
			        physicaltower.setNote(physicaltower.getDevicename()+sametower.toString()+"-"+dygt.getDevicename());
			        objMapper.updateByPrimaryKeySelective(physicaltower);
		        }
		    }//虚拟杆转虚拟杆
		    else if(!dygt.getDeviceid().equals(dygt.getPhysicaltowercode())&&!dygt.getDeviceid().equals(obj.getPhysicaltowercode())&&!dygt.getPhysicaltowercode().equals(obj.getPhysicaltowercode())){
		    	list=objMapper.getSameTowerList(dygt.getPhysicaltowercode());
		    	dygt.setSametowernumber(list.size()+1);
		    	result=objMapper.updateByPrimaryKeySelective(dygt);
		        StringBuffer sametower=new StringBuffer();
		        sametower.append("-"+dygt.getDevicename());
		        Dygt physicaltower=new Dygt();
	            if(list!=null&&list.size()>0){
	            	for(Dygt d:list){
		            	if(d.getDeviceid().equals(dygt.getPhysicaltowercode())){
		            		continue;
		            	}
		                d.setSametowernumber(list.size()+1);
//		                    d.setPhysicaltowercode(dygt.getPhysicaltowercode());
	                    d.setLastmodifiedtime(modifytime);
	                    d.setLastoperatorid(dygt.getLastoperatorid());
	                    objMapper.updateByPrimaryKeySelective(d);
	                    sametower.append("-"+d.getDevicename());
	                }
	            	physicaltower=load(dygt.getPhysicaltowercode());
			        if(list.size()==1){
			        	physicaltower.setIssametower("是");
			        }
			        physicaltower.setSametowernumber(list.size()+1);
			        physicaltower.setLastmodifiedtime(modifytime);
			        physicaltower.setLastoperatorid(dygt.getLastoperatorid());
			        physicaltower.setNote(physicaltower.getDevicename()+sametower.toString()+"-"+dygt.getDevicename());
			        objMapper.updateByPrimaryKeySelective(physicaltower);
	            }
		        //清空sametower中的内容
		        sametower=new StringBuffer();
		        List<Dygt> olist=objMapper.getSameTowerList(obj.getPhysicaltowercode());
	            if(olist!=null&&olist.size()>0){
	            	for(Dygt d:olist){
		            	if(d.getDeviceid().equals(obj.getPhysicaltowercode())){
		            		continue;
		            	}
		                d.setSametowernumber(olist.size());
//		                    d.setPhysicaltowercode(dygt.getPhysicaltowercode());
	                    d.setLastmodifiedtime(modifytime);
	                    d.setLastoperatorid(dygt.getLastoperatorid());
	                    objMapper.updateByPrimaryKeySelective(d);
	                    sametower.append("-"+d.getDevicename());
	                }
			        physicaltower=load(obj.getPhysicaltowercode());
			        if(olist.size()==1){
			        	physicaltower.setIssametower("否");
			        }
			        physicaltower.setLastmodifiedtime(modifytime);
			        physicaltower.setLastoperatorid(dygt.getLastoperatorid());
			        physicaltower.setSametowernumber(olist.size());
			        physicaltower.setNote(physicaltower.getDevicename()+sametower.toString());
			        objMapper.updateByPrimaryKeySelective(physicaltower);
	            }
		    }//当修改杆塔名称时
		    else if(!obj.getDevicename().equals(dygt.getDevicename())){
		    	list=objMapper.getSameTowerList(dygt.getPhysicaltowercode());
		    	if(list!=null&&list.size()>0){
		    		StringBuffer sametower=new StringBuffer();
		    		for(Dygt d:list){
		    			if(d.getDeviceid().equals(dygt.getPhysicaltowercode())){
		    				continue;
		    			}
		    			sametower.append("-"+d.getDevicename());
		    		}
		    		Dygt physicaltower=load(dygt.getPhysicaltowercode());
		    		physicaltower.setNote(physicaltower.getDevicename()+sametower.toString());
		    		physicaltower.setLastmodifiedtime(modifytime);
		    		physicaltower.setLastoperatorid(dygt.getLastoperatorid());
		    		objMapper.updateByPrimaryKeySelective(physicaltower);
		    	}
		    }else{
		        result=objMapper.updateByPrimaryKeySelective(dygt);
		    }
		}catch(DataAccessException e){
			_logger.error(ExceptionUtils.getStackTrace(e));
			throw new PwtzDatabaseException();
		}
		return result;
	}

	@Override
	public Dygt load(String deviceId) throws PwtzDatabaseException {
		if(_logger.isDebugEnabled()){
			_logger.debug("load:deviceId="+deviceId);
		}
		Dygt dygt=null;
		try{
			dygt=objMapper.selectByPrimaryKey(deviceId);
		}catch(DataAccessException e){
			_logger.error(ExceptionUtils.getStackTrace(e));
			throw new PwtzDatabaseException();
		}
		if(dygt!=null){
			_logger.debug("load:result dygt="+dygt.toString());
		}
		return dygt;
	}

	@Override
	public PaginationList<Dygt> selectDygts(String devicename,Long companyId,int portalType,String[]medLineCodes,String lineCode,String beginTime, String endTime,
			int pageSize, int pageNo,String currentDeviceId) throws PwtzDatabaseException{
		PaginationList<Dygt> dygts=new PaginationList<Dygt>();
		if(_logger.isInfoEnabled()){
		    _logger.info("selectDagts:|devicename=" + devicename+"|beginTime=" + beginTime+"|endTime=" + endTime+"|companyId="+companyId+"|portalType="+portalType+"|medLineCodes="+PwtzUtils.parseCharacterArrayToString(medLineCodes)+"|lineCode="+lineCode+"|pageSize="+pageSize+"|pageNo="+pageNo);
		}
		List<Dygt> list=null;
		int beginIndex = pageSize * pageNo - pageSize;
		String companyidStr="";
		String [] companyids=null;
		try{
			if(portalType==1){
				companyidStr=companyService.findChildrensId(companyId,null);
				if(companyidStr!=null&&companyidStr.length()>0){
					companyidStr=companyidStr.substring(0, companyidStr.length()-1);
					companyids=companyidStr.split(",");
				}
			}
			list=objMapper.selectDeviceList(devicename,portalType,medLineCodes,lineCode,companyids,companyId,beginTime, endTime, beginIndex, pageSize,currentDeviceId);
		}catch(DataAccessException e){
			_logger.error(ExceptionUtils.getStackTrace(e));
			throw new PwtzDatabaseException();
		}
		if(list !=null){
			_logger.debug("selectDygts:result list="+list.toString());
		}
		int totalCount = 0;
        int totalPage =1;
        if(pageSize!=0){
            try
            {
                totalCount = objMapper.selectDeviceCount(devicename,portalType,medLineCodes,lineCode,companyids,companyId,beginTime,endTime);
            }
            catch (DataAccessException e)
            {
                _logger.error(ExceptionUtils.getStackTrace(e));
                throw new PwtzDatabaseException();
            }
            totalPage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
        }else{
            pageNo=1;
            if(list!=null && list.size()>0){
                totalCount = list.size();
            }
        }
        dygts.setTotalPage(totalPage);
        dygts.setCurrPage(pageNo);
        dygts.setPageSize(pageSize);
        dygts.setRecords(list);
        dygts.setTotalRecord(totalCount);
		return dygts;
	}

    @Override
    public List<Dygt> getSameList(String deviceid) throws PwtzDatabaseException
    {
        if(_logger.isDebugEnabled()){
            _logger.debug("getSameList:deviceid="+deviceid);
        }
        if(deviceid==null||deviceid==""){
            if(_logger.isDebugEnabled()){
                _logger.debug("getSameList,deviceid is disable");
            }
            return null;
        }
        List<Dygt> list=null;
        try{
            list=objMapper.getDeviceList(deviceid);
            if(list==null){
                list=new ArrayList<Dygt>();
            }
        }catch(DataAccessException e){
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        return list;
    }

    @Override
    public boolean deleteDevice(String deviceid) throws PwtzDatabaseException, CanNotDeleteException
    {
        boolean flag=true;
        if(_logger.isDebugEnabled()){
            _logger.debug("getSameList:deviceid="+deviceid);
        }
        if(deviceid==null||deviceid==""){
            if(_logger.isDebugEnabled()){
                _logger.debug("getSameList,deviceid is disable");
            }
            return flag=false;
        }
        List<Dygt> list=null;
        int result=0;
        try{
            list=getSameList(deviceid);
            if(list!=null&&list.size()>0){
                for(Dygt device : list){
                    if(device.getDeviceid().equals(deviceid)){
                        continue;
                    }
                    if(device.getDeviceid().equals(device.getPhysicaltowercode())||getSameList(device.getDeviceid())!=null){
                        deleteDevice(device.getDeviceid());
                    }
                    result=delete(device.getDeviceid());
                    if(result==0){
                        flag=false;
                        break;
                    }
                    
                }
            }
        }catch(DataAccessException e){
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        return flag;
    }
	
    public int getSameTowerNumber(String deviceid)throws PwtzDatabaseException{
        int result=0;
        if(_logger.isDebugEnabled()){
            _logger.debug("getSameTowerNumber : deviceid="+deviceid);
        }
        if(deviceid==""||deviceid==null){
            if(_logger.isDebugEnabled()){
                _logger.debug("getSameTowerNumber is disabled");
            }
            return result;
        }
        try{
            result=objMapper.getSameTowerNumber(deviceid);
        }catch(DataAccessException e){
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        return result;
    }
    
    public int getCompanyTowerCount(Long companyId) throws PwtzDatabaseException{
        int result=0;
        if(_logger.isDebugEnabled()){
            _logger.debug("getCompanyTowerCount : companyId="+companyId);
        }
        try{
            result=objMapper.getCompanyTowerCount(companyId);
        }catch(DataAccessException e){
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        return result;
    }

	@Override
	public List<Dygt> getPhysicalTowerList(String deviceid, Long companyid)
			throws PwtzDatabaseException, CanNotDeleteException {
		if(_logger.isDebugEnabled()){
            _logger.debug("getPhysicalTowerList:|deviceid="+deviceid+"|companyid="+companyid);
        }
        List<Dygt> list=null;
        try{
            list=objMapper.getPhysicalTowerList(deviceid,companyid);
        }catch(DataAccessException e){
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        return list;
	}
	@Override
	public int updateLastSyncDevice(Long companyId, String lastSyncTime)  throws PwtzDatabaseException{
		int result=0;
		try {
			result=objMapper.updateLastSyncDevice(companyId, lastSyncTime);
		} catch (DataAccessException e) {
			_logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
		}
		return result;
	}
}
